import socketserver
import threading


class MyRequestHandler(socketserver.BaseRequestHandler):
    def setup(self):
        super().setup()
        self.event = threading.Event()

    def handle(self):
        super().handle()
        with server.lock:
            server.clients[self.client_address] = self.request
        while not self.event.is_set():
            data = self.request.recv(1024)
            if not data or data == b'quit':
                with server.lock:
                    server.clients.pop(self.client_address)
                break
            msg = 'Message:{} from {}'.format(data.decode(), self.client_address).encode()
            with server.lock:
                for c in server.clients.values():
                    c.send(msg)

    def finish(self):
        super().finish()
        self.event.set()


server = socketserver.ThreadingTCPServer(('127.0.0.1', 60000), MyRequestHandler)
server.clients = {}
server.lock = threading.Lock()
threading.Thread(target=server.serve_forever, name='serve').start()

while True:
    cmd = input('>>>')
    if cmd == 'quit':
        server.server_close()
        break
    print(threading.enumerate())
    print(server.clients)

# 整体做的不错, 不过某些类里面用到的属性, 可以封装到类里面, 而不是在类里面调用外面的属性,这样的话, 也方便整理资源
